#include "devicemgt.h"

DeviceMgt::DeviceMgt(const QString& dbPath, QObject *parent)
    : QObject(parent),  m_dbPath(dbPath) {
}

DeviceMgt::~DeviceMgt() {

}

void DeviceMgt::onGetDeviceData(QTcpSocket *socket) {
    // 为每个线程生成唯一的连接名
    QString connName = QString("login_%1").arg(quintptr(QThread::currentThreadId()));
     // 限定数据库对象作用域
    QString Device;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connName); // 创建独立连接
        db.setDatabaseName(m_dbPath);
        db.setConnectOptions("QSQLITE_BUSY_TIMEOUT=2000");
        if (!db.open()) {
            qDebug() << "Database open failed:" << db.lastError().text();
            return;
        }
        // 显式绑定到当前连接
        QSqlQuery query(db);
        query.prepare("SELECT device_id, name, type, location, manufacturer, model, installation_date FROM devices");

        while (query.next()) {
            Device += query.value(0).toString() + "," +
                query.value(1).toString() + "," +
                query.value(2).toString() + "," +
                query.value(3).toString() + "," +
                query.value(4).toString() + "," +
                query.value(5).toString() + "," +
                query.value(6).toString() + "\n";
        }
        query.finish();
    }

    // 安全移除连接
    if (QSqlDatabase::contains(connName)) {
        QSqlDatabase::removeDatabase(connName);
    }
    emit onSendDeviceData(Device, socket);
}
